package io.jsen.meta.diff.field;

import io.jsen.meta.diff.feature.annotation.FeatureConfig;
import io.jsen.meta.diff.feature.annotation.MetaFieldFeature;
import lombok.Data;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * @author jsen
 * @date 2021/09/18
 **/
@Data
public class ConfigField {
    private Field field;
    private FeatureConfig config;

    public ConfigField() {
        this.config = FeatureConfig.empty();
    }

    public ConfigField(Field field) {
        if (field == null) {
            this.config = FeatureConfig.empty();
            return;
        }
        this.field = field;
        MetaFieldFeature annotation = field.getAnnotation(MetaFieldFeature.class);
        if (annotation != null) {
            this.config = FeatureConfig.parse(annotation);
        } else {
            this.config = FeatureConfig.empty();
        }
    }

    public ConfigField(Field field, FeatureConfig config) {
        this.field = field;
        this.config = config;
    }

    public ConfigField(FeatureConfig config) {
        this.config = config;
    }

    public String getName() {
        assert field != null;
        return field.getName();
    }

    public String getNameOrNull() {
        if (field == null) {
            return null;
        }
        return field.getName();
    }

    public Class<?> getType() {
        assert field != null;
        return field.getType();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        ConfigField that = (ConfigField) o;
        return Objects.equals(field, that.field);
    }

    @Override
    public int hashCode() {
        return Objects.hash(field);
    }
}
